from flask import Blueprint, render_template, request, session, redirect, url_for
from datetime import datetime, timedelta

from app.models import User

main_bp = Blueprint('main', __name__, template_folder='../templates')

WEEKDAYS_CN = ['星期一','星期二','星期三','星期四','星期五','星期六','星期日']

@main_bp.before_request
def require_login():
    if 'user_id' not in session:
        return redirect(url_for('auth.login'))

@main_bp.route('/timeline')
def timeline():
    # 1. 获取 current_date（同你原逻辑）
    ds = request.args.get('date')
    try:
        current_date = datetime.strptime(ds, '%Y-%m-%d').date() if ds else datetime.today().date()
    except ValueError:
        current_date = datetime.today().date()

    # 2. 前/后一天
    prev_date = current_date - timedelta(days=1)
    next_date = current_date + timedelta(days=1)

    # 3. 生成前端显示的“2025年6月30日 星期一”格式
    display_date = current_date.strftime('%Y年%m月%d日') + ' ' + WEEKDAYS_CN[current_date.weekday()]

    # 4. 测试数据（实际请从 DB 取）
    data_list = [
        dict(time_hour=8, time_min=0, course='高等数学', teacher='张教授', room='逸夫楼201', time_range='08:00–09:40', status='未上'),
        # … 其他课程 …
    ]

    user = User.query.get(session['user_id'])

    current_user = 'admin'
    return render_template(
        'timeline.html',
        current_date=current_date,   # 如果后续还需要真实 date object
        display_date=display_date,   # 给模板用
        prev_date=prev_date,
        next_date=next_date,
        data_list=data_list,
        current_user=current_user,
        is_admin=user.is_admin
    )
